package com.yiya.ms.action;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.yiya.bean.CompanyUserInfo;
import com.yiya.bean.SysRole;
import com.yiya.bean.SysUser;
import com.yiya.bean.BaseBean.DELETED;
import com.yiya.bean.BaseBean.STATE;
import com.yiya.exception.ServiceException;
import com.yiya.model.CompanyCplex;
import com.yiya.model.CompanyCplexModel;
import com.yiya.model.CompanyUserInfoModel;
import com.yiya.model.CompanyUserInfoReceiveModel;
import com.yiya.model.SysUserModel;
import com.yiya.ms.annotation.Auth;
import com.yiya.service.CompanyService;
import com.yiya.service.CompanyUserInfoService;
import com.yiya.service.MailService;
import com.yiya.service.SysRoleService;
import com.yiya.service.SysUserService;
import com.yiya.utils.HtmlUtil;
import com.yiya.utils.MethodUtil;
import com.yiya.utils.SessionUtils;

@Controller
@RequestMapping("/companyUserInfo")
public class CompanyUserInfoAction extends BaseAction {
	@SuppressWarnings("unused")
	private final static Logger log= Logger.getLogger(CompanyUserInfoAction.class);

	@Autowired
	private SysUserService<SysUser> sysUserService;
	
	@Autowired(required=false) 
	private SysRoleService<SysRole> sysRoleService; 
	
	@Autowired
	private CompanyUserInfoService companyUserInfoService;
	
	@Autowired
	private CompanyService companyService;
	
	@Autowired
	private MailService mailService;
	
	@RequestMapping("/list") 
	public ModelAndView  list(SysUserModel model,HttpServletRequest request) throws Exception{
		Map<String,Object>  context = getRootMap();
		return forword("cpyUserInfo/cpyUserInfo",context); 
	}
	
	@RequestMapping("/dataList") 
	public void  dataList(SysUserModel model,HttpServletRequest request,HttpServletResponse response) throws Exception{
		model.setUserType(2);
		SysUser u = SessionUtils.getUser(request);
		if(u.getSuperAdmin()!=1){
			CompanyUserInfo userInfo = companyUserInfoService.queryByUserId(u.getId());
			model.setCompanyId(userInfo.getCompanyId());
		}
		List<SysUser> dataList = sysUserService.queryByList(model);
		for(SysUser user: dataList){
			List<SysRole> list = sysRoleService.queryByUserid(user.getId());
			user.setRoleStr(rolesToStr(list));
		}
		//设置页面数据
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		jsonMap.put("total",model.getPager().getRowCount());
		jsonMap.put("rows", dataList);
		HtmlUtil.writerJson(response, jsonMap);
	}
	
	@RequestMapping("/save")
	public void save(CompanyUserInfoReceiveModel bean,HttpServletRequest request,HttpServletResponse response) throws Exception{
		if(bean!=null){
			SysUser user = SessionUtils.getUser(request);
			Date nowTime = new Date();
			SysUser sysUser = new SysUser();
			sysUser.setId(bean.getSysUserId());
			sysUser.setEmail(bean.getEmail());
			sysUser.setNickName(bean.getNickName());
			sysUser.setState(bean.getState());
			sysUser.setUserType(bean.getUserType());
			sysUser.setCompanyId(bean.getCompanyId());
			sysUser.setDeleted(0);
			CompanyUserInfo companyUserInfo = new CompanyUserInfo();
			companyUserInfo.setId(bean.getCpyUserInfoId());
			companyUserInfo.setName(sysUser.getNickName());
			companyUserInfo.setMobileNumber(bean.getMobileNumber());
			companyUserInfo.setCompanyId(bean.getCompanyId());
			int count = sysUserService.getUserCountByEmail(sysUser.getEmail());
			if(sysUser.getId()==null){
				if(count>0){
					throw new ServiceException("用户已存在.");
				}
				sysUser.setCreateBy(user.getId());
				sysUserService.addSysUser(sysUser);
				companyUserInfo.setUserId(sysUser.getId());
				companyUserInfo.setCreateBy(user.getId());
				companyUserInfo.setCreateTime(nowTime);
				companyUserInfoService.add(companyUserInfo);
			}else{
				if(count > 1){
					throw new ServiceException("用户已存在.");
				}
				sysUser.setUpdateBy(user.getId());
				sysUserService.updateBySelective(sysUser);
				int cpyUserInfoCount = companyUserInfoService.getCpyUserInfoCountByUserId(sysUser.getId());
				if(cpyUserInfoCount==0){
					companyUserInfo.setUserId(sysUser.getId());
					companyUserInfo.setCreateBy(user.getId());
					companyUserInfo.setCreateTime(nowTime);
					companyUserInfoService.add(companyUserInfo);
				}else{
					companyUserInfo.setUpdateBy(user.getId());
					companyUserInfo.setUpdateTime(nowTime);
					companyUserInfoService.updaeBySelective(companyUserInfo);
				}
			}
			sendSuccessMessage(response, "保存成功");
		}else{
			sendFailureMessage(response, "保存失败");
		}
	}
	
	/**
	 * 角色列表转成字符串
	 * @param list
	 * @return
	 */
	private String rolesToStr(List<SysRole> list){
		if(list == null || list.isEmpty()){
			return null;
		}
		StringBuffer str = new StringBuffer();
		for(int i=0;i<list.size();i++){
			SysRole role = list.get(i);
			str.append(role.getRoleName());
			if((i+1) < list.size()){
				str.append(",");
			}
		}
		return str.toString();
	}
	
	@RequestMapping("/getId")
	public void getId(Integer id,HttpServletResponse response) throws Exception{
		Map<String,Object>  context = getRootMap();
		SysUser sysUser  = sysUserService.queryById(id);
		CompanyUserInfo companyUserInfo = companyUserInfoService.queryByUserId(id);
		if(sysUser  == null){
			sendFailureMessage(response, "没有找到对应的记录!");
			return;
		}
		CompanyUserInfoModel bean = new CompanyUserInfoModel();
		bean.setSysUser(sysUser);
		bean.setCompanyUserInfo(companyUserInfo);
		context.put(SUCCESS, true);
		context.put("data", bean);
		HtmlUtil.writerJson(response, context);
	}
	
	@RequestMapping("/delete")
	public void delete(Integer[] id,HttpServletResponse response) throws Exception{
		sysUserService.delete(id);
		sendSuccessMessage(response, "删除成功");
	}
	
	/**
	 * 添加或修改数据
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/updatePwd")
	public void updatePwd(Integer id,String oldPwd,String newPwd,HttpServletRequest request,HttpServletResponse response) throws Exception{
		boolean isAdmin = SessionUtils.isAdmin(request); //是否超级管理员
		SysUser bean  = sysUserService.queryById(id);
		if(bean.getId() == null || DELETED.YES.key == bean.getDeleted()){
			sendFailureMessage(response, "Sorry ,User is not exists.");
			return;
		}
		if(StringUtils.isBlank(newPwd)){
			sendFailureMessage(response, "Password is required.");
			return;
		}
		//不是超级管理员，匹配旧密码
		if(!isAdmin && !MethodUtil.ecompareMD5(oldPwd,bean.getPwd())){
			sendFailureMessage(response, "Wrong old password.");
			return;
		}
		bean.setPwd(MethodUtil.MD5(newPwd));
		sysUserService.update(bean);
		sendSuccessMessage(response, "保存成功~");
	}
	
	@Auth(verifyLogin=false,verifyURL=false)
	@RequestMapping("/toRegist")
	public void toRegist(CompanyUserInfoReceiveModel bean,HttpServletRequest request,HttpServletResponse response) throws Exception{
		Map<String,Object> context = getRootMap();
		CompanyCplexModel param = new CompanyCplexModel();
		List<CompanyCplex> companies = companyService.getCompanyList(param);
		context.put("companies", companies);
		
		String vcode  = SessionUtils.getValidateCode(request);
		SessionUtils.removeValidateCode(request);//清除验证码，确保验证码只能用一次
		
		if(bean!=null){
			if(StringUtils.isBlank(bean.getVerifyCode())){
				sendFailureMessage(response, "验证码不能为空.");
				return;
			}
			//判断验证码是否正确
			if(!bean.getVerifyCode().toLowerCase().equals(vcode)){
				sendFailureMessage(response, "验证码输入错误.");
				return;
			}
			Date nowTime = new Date();
			SysUser sysUser = new SysUser();
			sysUser.setId(bean.getSysUserId());
			sysUser.setEmail(bean.getEmail());
			sysUser.setNickName(bean.getNickName());
			sysUser.setPwd(MethodUtil.MD5(bean.getPwd()));
			sysUser.setState(2);//设置为未校验
			sysUser.setUserType(2);
			sysUser.setCompanyId(bean.getCompanyId());
			sysUser.setDeleted(0);
			CompanyUserInfo companyUserInfo = new CompanyUserInfo();
			companyUserInfo.setId(bean.getCpyUserInfoId());
			companyUserInfo.setName(sysUser.getNickName());
			companyUserInfo.setMobileNumber(bean.getMobileNumber());
			companyUserInfo.setCompanyId(bean.getCompanyId());
			int count = sysUserService.getUserCountByEmail(sysUser.getEmail());
			if(count>0){
				sendFailureMessage(response, "用户已存在.");
				return;
			}
			sysUserService.addSysUser(sysUser);
			companyUserInfo.setUserId(sysUser.getId());
			companyUserInfo.setCreateTime(nowTime);
			companyUserInfoService.add(companyUserInfo);
		
			mailService.sendValidateMail(sysUser.getId());
			sendSuccessMessage(response, "注册成功，请到邮箱及时完成校验");
		}else{
			sendFailureMessage(response, "注册失败");
		}
	}
	
	/**
	 * 用户授权页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/userRole") 
	public ModelAndView  userRole(HttpServletRequest request) throws Exception{
		Map<String,Object>  context = getRootMap();
		return forword("/cpyUserInfo/sysUserRole", context);
	}
	
	/**
	 * 用户授权列表
	 * @param model
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/userList") 
	public void  userList(SysUserModel model,HttpServletRequest request,HttpServletResponse response) throws Exception{
		model.setState(STATE.ENABLE.key);
		dataList(model,request,response);
	}
	
	@RequestMapping("/loadRoleList")
	public void loadRoleList(HttpServletResponse response) throws Exception{
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("roleType", 2);
		List<SysRole>  roloList = sysRoleService.queryAllList(param);
		HtmlUtil.writerJson(response, roloList);
	}

}
